package day0224;

import java.util.Iterator;

/**
 * 存 数据(值/对象) 的容器
 */
public class Container implements Iterable{

    /**
     * 存数据的对象数组
     */
    private Object[] objs;

    /**
     * 元素的数量
     */
    private int count;

    private static final int DEFAULT_SIZE = 10;

    public Container() {
        objs = new Object[DEFAULT_SIZE];
    }

    public Container(int size) {
        if (size >= 0) {
            objs = new Object[size];
        } else {
            objs = new Object[DEFAULT_SIZE];
        }
    }

    public void add(Object element) {
        objs[count] = element;
        count ++;
        // objs[count ++] = element;
    }

    public int getCount() {
        return this.count;
    }

    public Object getElement(int index) {
        if (index >= 0 && index < count) {
            return objs[index];
        }
        return null;
    }

    public int search(Object obj) {
        for (int i = 0; i < count; i++) {
            if (objs[i].equals(obj)){
                return i;
            }
        }
        return -1;
    }

    
    public static void main(String[] args) {
        Container container = new Container(3);

        container.add(1);
        container.add("a");

        System.out.println(container.getCount());

        for (int i = 0; i < container.getCount(); i++) {
            System.out.println(container.getElement(i));
        }

    }

    @Override
    public Iterator iterator() {
        // 迭代器
        return new ContainerIterator(this);
    }
}

class ContainerIterator implements Iterator{

    private Container container;

    private int current;

    public ContainerIterator(Container container){
        this.container = container;
    }

    /**
     * 判断是否还有下一个元素
     * @return
     */
    @Override
    public boolean hasNext() {
        return this.current < container.getCount() - 1;
    }

    /**
     * 获取元素
     * @return
     */
    @Override
    public Object next() {
        return container.getElement(current ++);
    }
}
